package com.javaee.controller.admin;

import com.javaee.entity.Admin;
import com.javaee.service.admin.AdminService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "admin/login";
    }
    @RequestMapping("/login")
    public String login(Admin admin, HttpSession session, Model model){
        String result = adminService.login(admin);
        if ("登录成功".equals(result)) {
            session.setAttribute("Admin", admin);
            return "redirect:/doctor/selectAllDoctorsByPage?currentPage=1";
        } else if ("用户名错误".equals(result)) {
            model.addAttribute("msg", "用户名错误");
            return "admin/login";
        } else if ("密码错误".equals(result)) {
            model.addAttribute("msg", "密码错误");
            return "admin/login";
        }
        model.addAttribute("msg", "登录失败，请稍后再试");
        return "admin/login";
    }
    @RequestMapping("/toUpdatePwd")
    public String toUpdatePwd(){
        return "admin/updatePwd";
    }
    @RequestMapping("/updatePwd")
    public String updatePwd(@RequestParam("username") String username, @RequestParam("password")String password, Model model){
        try {
            adminService.updatePwd(username, password);
            model.addAttribute("msg", "修改密码成功！");
        } catch (Exception e) {
            model.addAttribute("msg", "密码修改失败，请稍后再试。");
        }
        return "admin/updatePwd";
    }
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/";
    }
}
